# AppManager
from typing import Dict, Tuple, Any
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from common.app_registry import AppRegistry

class AppManager(object):
    def __init__(self):
        self.name = 'common.app_manager.AppManager'

    @staticmethod
    def init_app(params:Dict = {}) -> int:
        '''
        initialize the app. 
        return 0 is OK, others are errors.
        '''
        AppRegistry.fig, AppRegistry.ax, AppRegistry.axs = AppManager.init_matplotlib(rows=params['rows'], cols=params['cols'])
        return 0

    @staticmethod
    def init_matplotlib(rows:int, cols:int) -> Tuple[Any, Any, Any]:
        '''
        Called by every app class. 
        '''
        font_path = 'config/fonts/simhei.ttf'
        font_prop = fm.FontProperties(fname=font_path)
        font_name = font_prop.get_name()
        # fm.FontManager.addfont(font_path)
        fm.fontManager.addfont(font_path)
        # 指定系统自带的中文字体（根据系统选择）
        plt.rcParams['font.sans-serif'] = [font_name]  # 黑体（Windows）
        # plt.rcParams['font.sans-serif'] = ['Heiti TC']  # 黑体（macOS）
        # plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei']  # Linux
        plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
        # 创建双图布局
        fig, axs = plt.subplots(rows, cols, figsize=(10, 12), sharex=True)
        if rows*cols == 1:
            return fig, axs, None
        else:
            return fig, None, axs
